﻿using System;

namespace test
{

    public interface IObserver
    {
        ISubject Subject
        {
            set;
        }
    }

    public interface ISubject
    {
    }

    class Class1
    {
        [STAThread]
        static void Main2(string[] args)
        {
            int i;
            CatClass catsubject = new CatClass();

            for (i = 0; i < 10; i++)
            {
                RatClass rat = new RatClass();
                rat.Subject = catsubject;
            }

            ManClass man = new ManClass();
            man.Subject = catsubject;

            catsubject.Miao();
            Console.ReadLine();

        }
    }

    public class CatClass : ISubject
    {
        #region ICat 成员
        public delegate void CatEventHandler(object source, EventArgs e);
        public event CatEventHandler CatEvent;

        public void Miao()
        {
            Console.WriteLine("喵");
            if (CatEvent != null)
            {
                CatEvent(this, EventArgs.Empty);
            }
        }

        #endregion
    }

    public class RatClass : IObserver
    {
        #region IObserver 成员

        CatClass cat = null;
        public ISubject Subject
        {
            set
            {
                cat = (CatClass)value;
                cat.CatEvent += new test.CatClass.CatEventHandler(Run);
            }
        }

        #endregion


        public void Run(object source, EventArgs e)
        {
            Console.WriteLine("猫来了，赶紧跑！！！");
        }

    }

    public class ManClass : IObserver
    {
        CatClass cat = null;
        #region IObserver 成员

        public ISubject Subject
        {
            set
            {
                cat = (CatClass)value;
                cat.CatEvent += new test.CatClass.CatEventHandler(Wake);
            }
        }

        #endregion

        private void Wake(object source, EventArgs e)
        {
            Console.WriteLine("主人被吵醒");
        }
    }

}
